<template>
	<div class="sys-editCodeGen-container">
		<el-dialog v-model="state.isShowDialog" draggable :close-on-click-modal="false" width="1400px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit />
					</el-icon>
					<span> {{ props.title }} </span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="库定位器" prop="configId">
							<el-select v-model="state.ruleForm.configId" placeholder="库名" filterable
								@change="dbChanged()" class="w100">
								<el-option v-for="item in state.dbData" :key="item.configId" :label="item.configId"
									:value="item.configId" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="库类型" prop="dbType"
							:rules="[{ required: true, message: '描述不能为空', trigger: 'blur' }]">
							<el-select v-model="state.ruleForm.dbType" placeholder="数据库类型" clearable disabled
								class="w100">
								<el-option label="MySql" :value="'0'" />
								<el-option label="SqlServer" :value="'1'" />
								<el-option label="Sqlite" :value="'2'" />
								<el-option label="Oracle" :value="'3'" />
								<el-option label="PostgreSQL" :value="'4'" />
								<el-option label="Dm" :value="'5'" />
								<el-option label="Kdbndp" :value="'6'" />
								<el-option label="Oscar" :value="'7'" />
								<el-option label="MySqlConnector" :value="'8'" />
								<el-option label="Access" :value="'9'" />
								<el-option label="OpenGauss" :value="'10'" />
								<el-option label="QuestDB" :value="'11'" />
								<el-option label="HG" :value="'12'" />
								<el-option label="ClickHouse" :value="'13'" />
								<el-option label="GBase" :value="'14'" />
								<el-option label="Custom" :value="'900'" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="库地址" prop="connectionString">
							<el-input v-model="state.ruleForm.connectionString" disabled clearable type="textarea" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="生成表" prop="tableName"
							:rules="[{ required: true, message: '生成表不能为空', trigger: 'blur' }]">
							<el-select v-model="state.ruleForm.tableName" filterable clearable class="w100">
								<el-option v-for="item in state.tableData" :key="item.entityName"
									:label="item.entityName + ' ( ' + item.tableName + ' )'" :value="item.entityName" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="业务名" prop="busName">
							<el-input v-model="state.ruleForm.busName" placeholder="请输入" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="父级菜单" prop="menuPid">
							<el-cascader :options="state.menuData"
								:props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'title' }"
								placeholder="请选择上级菜单" clearable class="w100" v-model="state.ruleForm.menuPid">
								<template #default="{ node, data }">
									<span>{{ data.title }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<!-- <el-form-item label="命名空间(代码生成的类库)" prop="nameSpace">
							<el-input v-model="state.ruleForm.nameSpace" clearable placeholder="请输入" />
						</el-form-item> -->
						<el-form-item label="命名空间(代码生成的类库)" prop="nameSpace"
							:rules="[{ required: true, message: '命名空间能为空', trigger: 'blur' }]">
							<el-select v-model="state.ruleForm.nameSpace" filterable clearable class="w100">
								<el-option v-for="item in state.nameSpaceData" :key="item" :label="item"
									:value="item" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="作者姓名" prop="authorName">
							<el-input v-model="state.ruleForm.authorName" clearable placeholder="请输入" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="生成方式" prop="generateType">
							<el-select v-model="state.ruleForm.generateType" filterable class="w100">
								<el-option v-for="item in state.codeGenTypeList" :key="item.value" :label="item.value"
									:value="item.code" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="开启历史记录表" prop="temp1">
							 <el-checkbox v-model="state.ruleForm.temp1" size="small"/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="列表多选" prop="temp2">
							 <el-checkbox v-model="state.ruleForm.temp2" size="small"/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="做为子组件加载字段名" prop="temp3">
							<el-input v-model="state.ruleForm.temp3" clearable placeholder="做为子组件加载字段名" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="App使用自定义导航栏" prop="temp4">
							  <el-checkbox v-model="state.ruleForm.temp4" label="使用自定义导航栏" size="large" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="勾选框显示条件" prop="checkWhere">
							<el-input v-model="state.ruleForm.checkWhere" clearable placeholder="请输入勾选框显示条件" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="通用按钮权限" prop="normalButtons">
							  <el-checkbox  :label="item.desc" v-model="item.isUse" size="small" v-for="(item, index) in state.ruleForm.normalButtons"/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<!-- 非页面配置 -->
						<el-form-item label="复制其它表配置" prop="copyOtherTableConfig">
							<el-input v-model="state.ruleForm.copyOtherTableConfig" clearable placeholder="请输入复制其它表配置" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="重写API服务" prop="copyOtherTableConfig">
							<el-input v-model="state.ruleForm.temp5" clearable placeholder="请输入重写API服务" />
						</el-form-item>
					</el-col>
					
				<el-col :xs="24" class="mb20">
						<el-button type="primary" @click="addFruitConfig" class="mb20">新增组件</el-button>
						<el-row :gutter="2" v-for="(item, index) in state.ruleForm.comments">
							<el-col :span="2"  class="mb20">	
							<el-select v-model="item.buttonName" placeholder="按钮名称"
							 clearable filterable allow-create default-first-option class="w100"
							 @change="addComponentChange($event,item)" >
								<el-option label="新增明细" value="新增明细" />
								<el-option label="展开行" value="展开行" />
							</el-select>
							</el-col>
							<el-col :span="2" class="mb20">
								<el-input v-model="item.buttonAuth" :disabled="item.disabled" clearable placeholder="按钮权限名称" />
							</el-col>
							<el-col :span="2" class="mb20">
								<el-input v-model="item.commentName" :disabled="item.disabled" clearable placeholder="组件名称" />
							</el-col>
							<el-col :span="3" class="mb20">
								<el-input v-model="item.commentPathTemp" clearable placeholder="组件路径,如:/@/views/./index.vue" />
							</el-col>
							<el-col :span="2" class="mb20">
								<el-input v-model="item.assField" clearable placeholder="關聯字段" />
							</el-col>
							<el-col :span="2" class="mb20">
						       <el-input v-model="item.disabledWhere" clearable placeholder="禁用/行颜色/条件" />
							</el-col>
							<el-col :span="3" class="mb20">
								<el-select v-model="item.addOrUpdate" :disabled="item.disabled" placeholder="新增或修改" clearable class="w100">
									<el-option label="弹框新增(.openDialog(null))" :value="'add'" />
									<el-option label="弹框修改(.openDialog(row))" :value="'update'" />
								</el-select>
							</el-col>
							<el-col :span="4" class="mb20">
								<el-select v-model="item.isMultipleOperation" placeholder="组件信息" clearable class="w100">
									<el-option label="多行选中操作按钮-弹框" :value="'Y'" />
									<el-option label="多行选中操作按钮-纯按钮" :value="'YB'" />
									<el-option label="单行操作按钮-弹框" :value="'N'" />
									<el-option label="单行操作按钮-纯按钮" :value="'NB'" />
									<el-option label="展开行" :value="'E'" />
									<el-option label="行颜色" :value="'C'" />
									<el-option label="页签" :value="'Tabs'" />
								</el-select>
							</el-col>
							<el-col :span="4" class="mb20">
								<el-button type="primary" @click.prevent="removeFruitConfig(item)">删除行</el-button>
							</el-col>
						</el-row>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup name="sysEditCodeGen">
	import { onMounted, reactive, ref } from 'vue';
	import request from '/@/utils/request';
	import { getAPI } from '/@/utils/axios-utils';
	import { SysCodeGenApi, SysDictDataApi, SysMenuApi } from '/@/api-services/api';
	import { UpdateCodeGenInput, AddCodeGenInput, SysMenu } from '/@/api-services/models';

	const props = defineProps({
		title: String,
	});
	const emits = defineEmits(['handleQuery']);
	const ruleFormRef = ref();
	const state = reactive({
		isShowDialog: false,
		ruleForm: {} as UpdateCodeGenInput,
		tableData: [] as any,
		dbData: [] as any,
		menuData: [] as Array<SysMenu>,
		nameSpaceData: [] as any,
		codeGenTypeList: [] as any,
		tempNormalButtons:[
        { desc: "新增", buttonName: "add", isUse: true},
        { desc:"删除", buttonName:"delete",isUse:true},
        { desc:"编辑", buttonName:"edit",isUse:true},
        { desc: "导出", buttonName: "export",isUse: true},
        { desc: "导入", buttonName: "import",isUse: true},
        { desc: "保存", buttonName: "save",isUse: true},
        { desc: "详情", buttonName: "detail",isUse: true},
        { desc: "下载导入模板", buttonName: "templateDown",isUse: true}
		]
	});
	
    
	const addFruitConfig = () => { // 新增水果、售价行
		if (state.ruleForm.comments == null || state.ruleForm.comments == undefined)
			state.ruleForm.comments = []
		state.ruleForm.comments.push({
			buttonName: '',
			buttonAuth: '',
			commentName:'',
			commentPath:'',
			commentPathTemp:'',
			isMultipleOperation:'Y',
			DisabledWhere:'',
			addOrUpdate:'update',
			disabled:false,
		})
	}

	const removeFruitConfig = (item) => { // 删除水果、售价行
		const index = state.ruleForm.comments.indexOf(item)
		if (index !== -1) {
			state.ruleForm.comments.splice(index, 1)
		}
	}

	onMounted(async () => {
		
		var resDb = await getAPI(SysCodeGenApi).apiSysCodeGenDatabaseListGet();
		state.dbData = resDb.data.result;
		console.log(state.dbData);
		var ccc = await request({
			url: `api/sysCodeGenConfig/GetCurrentAssemblyNames`,
			method: 'get'

		}).then(response => {
			return response;
		});
		state.nameSpaceData = ccc.data.result;
		console.log(state.nameSpaceData);
		console.log(ccc.data.result);
		// console.log(ccc.data.result);

		let resMenu = await getAPI(SysMenuApi).apiSysMenuListGet();
		state.menuData = resMenu.data.result ?? [];

		let resDicData = await getAPI(SysDictDataApi).apiSysDictDataDataListCodeGet('code_gen_create_type');
		state.codeGenTypeList = resDicData.data.result;
	});

	//获取命名空间下拉菜单数据
	const loadNameSpaces = async () => {

	}
	// db改变
	const dbChanged = async () => {
		if (state.ruleForm.configId === '') return;
		console.log(state.ruleForm.configId)
		let res = await getAPI(SysCodeGenApi).apiSysCodeGenTableListConfigIdGet(state.ruleForm.configId as string);
		state.tableData = res.data.result ?? [];

		let db = state.dbData.filter((u : any) => u.configId == state.ruleForm.configId);
		state.ruleForm.connectionString = db[0].connectionString;
		state.ruleForm.dbType = db[0].dbType.toString();
	};

	// 打开弹窗
	const openDialog = (row : any) => {
		state.ruleForm = JSON.parse(JSON.stringify(row));
		if(state.ruleForm.id == undefined){
			state.ruleForm.normalButtons =state.tempNormalButtons;
			state.ruleForm.temp2=true;
		}
		state.isShowDialog = true;
		ruleFormRef.value?.resetFields();
	};
    const addComponentChange=(value,item)=>{
		item.disabled=false;
		if(value=='新增明细'||value =='新增明細'){
			item.disabled=true;
			item.addOrUpdate=null;
			item.buttonAuth ='addBody';
			item.commentName='addBody';
		}
		else if(value=='展开行'||value =='展開行'){
			item.disabled=true;
			item.addOrUpdate=null;
			item.buttonAuth ='expand';
			item.commentName='expand';
		}
	};
	// 关闭弹窗
	const closeDialog = () => {
		emits('handleQuery');
		state.isShowDialog = false;
	};

	// 取消
	const cancel = () => {
		state.isShowDialog = false;
	};

	// 提交
	const submit = () => {
		ruleFormRef.value.validate(async (valid : boolean) => {
			if (!valid) return;
			if(state.ruleForm.comments!=undefined)
			state.ruleForm.comments.forEach(item=>{
				if(item.commentPathTemp!=null && item.commentPathTemp!='')
				 item.commentPath =`import ${item.commentName} from '${item.commentPathTemp}'`;
			});
			if (state.ruleForm.id != undefined && state.ruleForm.id > 0) {
				await getAPI(SysCodeGenApi).apiSysCodeGenUpdatePost(state.ruleForm as UpdateCodeGenInput);
			} else {
				await getAPI(SysCodeGenApi).apiSysCodeGenAddPost(state.ruleForm as AddCodeGenInput);
			}
			closeDialog();
		});
	};

	const isOrNotSelect = () => {
		return [
			{
				label: '是',
				value: 1,
			},
			{
				label: '否',
				value: 0,
			},
		];
	};

	// 导出对象
	defineExpose({ openDialog });
</script>